/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

final class Constants {
    public static int ID_IDLE = 0;
    public static int ID_WORKER = 1;
    public static int ID_HANDLER_A = 2;
    public static int ID_HANDLER_B = 3;
    public static int ID_DEVICE_A = 4;
    public static int ID_DEVICE_B = 5;
    public static int NUMBER_OF_IDS = 6;

    public static int KIND_DEVICE = 0;
    public static int KIND_WORK = 1;

    /**
     * The task is running and is currently scheduled.
     */
    public static int STATE_RUNNING = 0;

    /**
     * The task has packets left to process.
     */
    public static int STATE_RUNNABLE = 1;

    /**
     * The task is not currently running.  The task is not blocked as such and may
     * be started by the scheduler.
     */
    public static int STATE_SUSPENDED = 2;

    /**
     * The task is blocked and cannot be run until it is explicitly released.
     */
    public static int STATE_HELD = 4;

    public static int STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE;
    public static int STATE_NOT_HELD = ~STATE_HELD;
    public static int DATA_SIZE = 4;
    public static int COUNT = 1000;

    /**
     ** These two constants specify how many times a packet is queued and
     ** how many times a task is put on hold in a correct run of richards.
     ** They don't have any meaning a such but are characteristic of a
     ** correct run so if the actual queue or hold count is different from
     ** the expected there must be a bug in the implementation.
     **/
    public static int EXPECTED_QUEUE_COUNT = 2322;
    public static int EXPECTED_HOLD_COUNT = 928;
    // Generator
    // Base classes for different task type

}

 class BaseTask {
     /**
      * @State
      */
    public Scheduler scheduler;
    BaseTask(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public TaskControlBlock run(Packet packet) {
        return new TaskControlBlock(null,0,0,packet,null);
    }

    @Override
    public String toString() {
        return "BaseTask";
    }
}

class IdleTask extends BaseTask {
    public int v1;
    public int count;
    /**
     * An idle task doesn't do any work itself but cycles control between the two
     * device tasks.
     * @param {Scheduler} scheduler the scheduler that manages this task
     * @param {number} v1 a seed value that controls how the device tasks are scheduled
     * @param {number} count the number of times this task should be scheduled
     * @constructor
     */
    IdleTask(Scheduler scheduler, int v1, int count) {
        super(scheduler);
        this.v1 = v1;
        this.count = count;
    }
    @Override
    public TaskControlBlock run(Packet packet) {
        final int NUMBER_D008 = 0xd008;
        this.count -= 1;
        if (this.count == 0) {
            return this.scheduler.holdCurrent();
        }
        if ((this.v1 & 1) == 0) {
            this.v1 = this.v1 >> 1;
            // release ID_DEVICE_A
            return this.scheduler.release(Constants.ID_DEVICE_A);
        } else {
            this.v1 = (this.v1 >> 1) ^ NUMBER_D008;
            // release ID_DEVICE_B
            return this.scheduler.release(Constants.ID_DEVICE_B);
        }
    }

    @Override
    public String toString() {
        return "IdleTask";
    }
}

class WorkerTask extends BaseTask {

    int v1;
    int v2;
    /**
     * A task that manipulates work packets.
     * @param {Scheduler} scheduler the scheduler that manages this task
     * @param {number} v1 a seed used to specify how work packets are manipulated
     * @param {number} v2 another seed used to specify how work packets are manipulated
     * @constructor
     */
    WorkerTask(Scheduler scheduler, int v1, int v2) {
        super(scheduler);
        this.v1 = v1;
        this.v2 = v2;
    }

    public TaskControlBlock run(Packet packet) {
        if (packet == null) {
            return this.scheduler.suspendCurrent();
        } else {
            final int V2_MAX = 26;
            if (this.v1 == Constants.ID_HANDLER_A) {
                // swich v1 value
                this.v1 = Constants.ID_HANDLER_B;
            } else {
                this.v1 = Constants.ID_HANDLER_A;
            }
            // set packet id
            packet.id = this.v1;
            packet.a1 = 0;
            for (int i = 0; i < Constants.DATA_SIZE; i++) {
                this.v2 += 1;
                if (this.v2 > V2_MAX) {
                    this.v2 = 1;
                }
                packet.a2[i] = this.v2;
            }
            return this.scheduler.queue(packet);
        }
    }

    @Override
    public String toString() {
        return "WorkerTask";
    }
}

class HandlerTask extends BaseTask {
    // scheduler: Scheduler
    public Packet v1;
    public Packet v2;
    HandlerTask(Scheduler scheduler) {
        // this.scheduler=scheduler
        super(scheduler);
    }
    /**
     * A task that manipulates work packets and then suspends itself.
     * @param {Scheduler} scheduler the scheduler that manages this task
     * @constructor
     */
    public TaskControlBlock run(Packet packet) {
        if (packet != null) {
            if (packet.kind == Constants.KIND_WORK) {
                //  add packet v1
                this.v1 = packet.addTo(this.v1);
            } else {
                // add packet v2
                this.v2 = packet.addTo(this.v2);
            }
        }
        if (this.v1 != null) {
            int count = this.v1.a1;
            Packet v = this.v2;
            if (count < Constants.DATA_SIZE) {
                if (this.v2 != null) {
                    v = this.v2;
                    this.v2 = this.v2.link;
                    v.a1 = this.v1.a2[count];
                    this.v1.a1 = count + 1;
                    return this.scheduler.queue(v);
                }
            } else {
                v = this.v1;
                this.v1 = this.v1.link;
                return this.scheduler.queue(v);
            }
        }
        return this.scheduler.suspendCurrent();
    }

    @Override
    public String toString() {
        return "HandlerTask";
    }
}

/**
 * A task that suspends itself after each time it has been run to simulate
 * waiting for data from an external device.
 * @param {Scheduler} scheduler the scheduler that manages this task
 * @constructor
 */
//
class DeviceTask extends BaseTask {
    public Packet v1;
    // scheduler: Scheduler;

    DeviceTask(Scheduler scheduler) {
        super(scheduler);
    }
    /**
     * Runs this task, if it is ready to be run, and returns the next task to run.
     */
    public TaskControlBlock run(Packet packet) {
        if (packet == null) {
            if (this.v1 == null) {
                return this.scheduler.suspendCurrent();
            }
            Packet v = this.v1;
            this.v1 = null;
            return this.scheduler.queue(v);
        } else {
            this.v1 = packet;
            return this.scheduler.holdCurrent();
        }
    }

    @Override
    public String toString() {
        return "DeviceTask";
    }
}

class Packet {
    public Packet link;
    public int id;
    public int kind;
    public int a1;
    public int[] a2 = new int[Constants.DATA_SIZE];

    /**
     ** A simple package of data that is manipulated by the tasks.  The exact layout
     ** of the payload data carried by a packet is not importaint, and neither is the
     ** nature of the work performed on packets by the tasks.
     ** Besides carrying data, packets form linked lists and are hence used both as
     ** data and worklists.
     ** @param {Packet} link the tail of the linked list of packets
     ** @param {number} id an ID for this packet
     ** @param {number} kind the type of this packet
     ** @constructor
     **/
    Packet(Packet link, int id, int kind) {
        this.link = link;
        this.kind = kind;
        this.id = id;
    }

    /**
     * Add this packet to the end of a worklist, and return the worklist.
     * @param {Packet} queue the worklist to add this packet to
     */
    public Packet addTo(Packet queue) {
        this.link = null;
        if (queue == null) {
            return this;
        }
        Packet peek;
        Packet next = queue;
        while ((peek = next.link) != null) {
            next = peek;
        }
        next.link = this;
        return queue;
    }

    @Override
    public String toString() {
        return "packet";
    }
}

class TaskControlBlock {
    public TaskControlBlock link;
    public int id;
    public int priority;
    public Packet queue;
    public BaseTask task;
    public int state;

    /**
     * A task control block manages a task and the queue of work packages associated
     * with it.
     * @param {TaskControlBlock} link the preceding block in the linked block list
     * @param {number} id the id of this block
     * @param {number} priority the priority of this block
     * @param {Packet} queue the queue of packages to be processed by the task
     * @param {Task} task the task
     * @constructor
     */
    public TaskControlBlock(TaskControlBlock link, int id, int priority, Packet queue, BaseTask task ) {
        final int STATE_NUMBER_1 = 1;
        final int STATE_NUMBER_2 = 2;
        this.link = link;
        this.id = id;
        this.priority = priority;
        this.queue = queue;
        this.task = task;
        if (this.queue == null) {
            this.state = STATE_NUMBER_2;
        } else {
            this.state = STATE_NUMBER_2 | STATE_NUMBER_1;
        }
    }
    public void setRunning() {
        this.state = Constants.STATE_RUNNING;
    }

    public void markAsNotHeld() {
        this.state = this.state & Constants.STATE_NOT_HELD;
    }

    public void markAsHeld() {
        this.state = this.state | Constants.STATE_HELD;
    }

    public boolean isHeldOrSuspended() {
        return (this.state & Constants.STATE_HELD) != 0 || this.state == Constants.STATE_SUSPENDED;
    }

    public void markAsSuspended() {
        this.state = this.state | Constants.STATE_SUSPENDED;
    }

    public void markAsRunnable() {
        this.state = this.state | Constants.STATE_RUNNABLE;
    }
    /**
     * Runs this task, if it is ready to be run, and returns the next task to run.
     */
    public TaskControlBlock run() {
        Packet packet;
        if (this.state == Constants.STATE_SUSPENDED_RUNNABLE) {
            packet = this.queue;
            this.queue = packet.link;
            if (this.queue == null) {
                //queue is empty, set state STATE_RUNNING
                this.state = Constants.STATE_RUNNING;
            } else {
                //queue not empty, set state STATE_RUNNABLE
                this.state = Constants.STATE_RUNNABLE;
            }
        } else {
            packet = null;
        }
        return this.task.run(packet);
    }
    /**
     ** Adds a packet to the worklist of this block's task, marks this as runnable if
     ** necessary, and returns the next runnable object to run (the one
     ** with the highest priority).
     **/
    public TaskControlBlock checkPriorityAdd(TaskControlBlock task, Packet packet) {
        if (this.queue == null) {
            this.queue = packet;
            this.markAsRunnable();
            if (this.priority > task.priority) {
                return this;
            }
        } else {
            this.queue = packet.addTo(this.queue);
        }
        return task;
    }

    @Override
    public String toString() {
        String d = "";
        if (this.task != null) {
            d = "tcb {  (" + this.task + ") @ " + "(" + this.state + ") }";
        }
        return d;
    }
}

class Scheduler {
    public int queueCount;
    public int holdCount;
    public TaskControlBlock list;
    public TaskControlBlock currentTcb;
    public TaskControlBlock[] blocks;
    public int currentId;
    Scheduler(
            int queueCount,
            int holdCount,
            int currentId,
            TaskControlBlock list,
            TaskControlBlock currentTcb,
            TaskControlBlock[] blocks
    ) {
        this.queueCount = queueCount;
        this.holdCount = holdCount;
        this.currentId = currentId;
        this.list = list;
        this.currentTcb = currentTcb;
        this.blocks = blocks;
    }

    /**
     * Add an idle task to this scheduler.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     * @param {number} count the number of times to schedule the task
     */
    public void addIdleTask(int id, int priority, Packet queue, int count) {
        this.addRunningTask(id, priority, queue, new IdleTask(this, 1, count));
    }
    /**
     * Add a work task to this scheduler.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     */
    public void addWorkerTask(int id, int priority, Packet queue) {
        this.addTask(id, priority, queue, new WorkerTask(this, Constants.ID_HANDLER_A, 0));
    }

    /**
     * Add a handler task to this scheduler.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     */
    public void addHandlerTask(int id, int priority, Packet queue) {
        this.addTask(id, priority, queue, new HandlerTask(this));
    }

    /**
     * Add a handler task to this scheduler.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     */
    public void addDeviceTask(int id, int priority, Packet queue) {
        this.addTask(id, priority, queue, new DeviceTask(this));
    }

    /**
     * Add the specified task and mark it as running.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     * @param {Task} task the task to add
     */
    public void addRunningTask(int id, int priority, Packet queue, IdleTask task) {
        this.addTask(id, priority, queue, task);
        this.currentTcb.setRunning();
    }

    /**
     * Add the specified task to this scheduler.
     * @param {number} id the identity of the task
     * @param {number} priority the task's priority
     * @param {Packet} queue the queue of work to be processed by the task
     * @param {Task} task the task to add
     */
    public void addTask(int id, int priority, Packet queue, BaseTask task) {
        this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task);
        this.list = this.currentTcb;
        this.blocks[id] = this.currentTcb;
    }

    /**
     * Block the currently executing task and return the next task control block
     * to run.  The blocked task will not be made runnable until it is explicitly
     * released, even if new work is added to it.
     */
    public TaskControlBlock holdCurrent() {
        this.holdCount++;
        this.currentTcb.markAsHeld();
        return this.currentTcb.link;
    }

    /**
     * Suspend the currently executing task and return the next task control block
     * to run.  If new work is added to the suspended task it will be made runnable.
     */
    public TaskControlBlock suspendCurrent() {
        this.currentTcb.markAsSuspended();
        return this.currentTcb;
    }
    /**
     * Add the specified packet to the end of the worklist used by the task
     * associated with the packet and make the task runnable if it is currently
     * suspended.
     * @param {Packet} packet the packet to add
     */
    public TaskControlBlock queue(Packet packet) {
        TaskControlBlock t = this.blocks[packet.id];
        if (t == null) {
            return t;
        }
        this.queueCount++;
        packet.link = null;
        packet.id = this.currentId;
        return t.checkPriorityAdd(this.currentTcb, packet);
    }
    /**
     * Execute the tasks managed by this scheduler.
     */
    public void schedule() {
        this.currentTcb = this.list;
        while (this.currentTcb != null) {
            if (Benchmark.debug) {
                Benchmark.log(this.currentTcb.toString());
            }
            if (this.currentTcb.isHeldOrSuspended()) {
                this.currentTcb = this.currentTcb.link;
            } else {
                // set next tcb
                this.currentId = this.currentTcb.id;
                this.currentTcb = this.currentTcb.run();
            }
        }
    }
    /**
     ** Release a task that is currently blocked and return the next block to run.
     ** @param {int} id the id of the task to suspend
     **/
    public TaskControlBlock release(int id) {
        TaskControlBlock tcb = this.blocks[id];
        if (tcb == null) {
            return tcb;
        }
        tcb.markAsNotHeld();
        if (tcb.priority > this.currentTcb.priority) {
            return tcb;
        } else {
            return this.currentTcb;
        }
    }
}
/*
 * @State
 * @Tags Jetstream2
 */
 class Benchmark {
  /**
   * @Benchmark
   */
    public void runIteration() {
        final int TIME_RADIX = 1000;
        final int ITERATION_OUTER = 20;
        final int ITRATION_INNER = 50;
        double start = System.nanoTime() / 1_000_000.0;
        for (int j = 0; j < ITERATION_OUTER; j++) {
            for (int i = 0; i < ITRATION_INNER; i++) {
                runRichards();
            }
        }
        double end = System.nanoTime() / 1_000_000.0;
        System.out.println("richards: ms = " + (end - start));
    }
    public void runRichards() {
        final int PRIORITY_1 = 1000;
        final int PRIORITY_2 = 2000;
        final int PRIORITY_3 = 3000;
        final int PRIORITY_4 = 4000;
        final int PRIORITY_5 = 5000;
        Scheduler scheduler = new Scheduler(0, 0, 0, null, null, new TaskControlBlock[Constants.NUMBER_OF_IDS]);
        scheduler.addIdleTask(Constants.ID_IDLE, 0, null, Constants.COUNT);

        Packet queue = new Packet(null, Constants.ID_WORKER, Constants.KIND_WORK);
        queue = new Packet(queue, Constants.ID_WORKER, Constants.KIND_WORK);
        scheduler.addWorkerTask(Constants.KIND_WORK, PRIORITY_1, queue);
        //create DEVICE_A Packet
        queue = new Packet(null, Constants.ID_DEVICE_A, Constants.KIND_DEVICE);
        queue = new Packet(queue, Constants.ID_DEVICE_A, Constants.KIND_DEVICE);
        queue = new Packet(queue, Constants.ID_DEVICE_A, Constants.KIND_DEVICE);
        scheduler.addHandlerTask(Constants.ID_HANDLER_A, PRIORITY_2, queue);
        //create DEVICE_B Packet
        queue = new Packet(null, Constants.ID_DEVICE_B, Constants.KIND_DEVICE);
        queue = new Packet(queue, Constants.ID_DEVICE_B, Constants.KIND_DEVICE);
        queue = new Packet(queue, Constants.ID_DEVICE_B, Constants.KIND_DEVICE);
        scheduler.addHandlerTask(Constants.ID_HANDLER_B, PRIORITY_3, queue);
        // add task ID_DEVICE_A
        scheduler.addDeviceTask(Constants.ID_DEVICE_A, PRIORITY_4, null);
        // add task ID_DEVICE_B
        scheduler.addDeviceTask(Constants.ID_DEVICE_B, PRIORITY_5, null);

        scheduler.schedule();
        // status check
        if (scheduler.queueCount != Constants.EXPECTED_QUEUE_COUNT || scheduler.holdCount != Constants.EXPECTED_HOLD_COUNT) {
            String msg = "Error during execution: queueCount = " + scheduler.queueCount +  ", holdCount = " + scheduler.holdCount + ".";
            throw new Error(msg);
        } else {
            Benchmark.log("queueCount : " + scheduler.queueCount + "; holdCount : " + scheduler.holdCount);
        }
    }

    public static boolean debug = false;
    public static void log(String msg) {
        if (debug) {
            System.out.println(msg);
        }
    }
    public static void main(String[] args) {
        new Benchmark().runIteration();
    }
}